package pic.text.ocr.pic.text;

import pic.text.ocr.R;
import android.app.Activity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ocr extends Activity implements Runnable{
    

	
	private static final String TAG = ocr.class.getSimpleName();

	protected String url = "http://maggie.ocrgrid.org/cgi-bin/weocr/nhocr.cgi";

	private Bitmap bitmap;
	private Handler handler;
	
    protected DefaultHttpClient httpClient;
    HttpParams params;

	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bitmap = BitmapFactory.decodeFile("/Users/nebatsbeha/Desktop/bronze.jpg");
    }
    
    	//HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
       // HttpProtocolParams.setUseExpectContinue(params, true);
       // HttpConnectionParams.setConnectionTimeout(params, timeout);
  
    
    @Override
	public void run() {
		try {
			params = new BasicHttpParams();
		    httpClient = new DefaultHttpClient(params);
			String ocredText = sendOcrRequest(bitmap);
			Log.d(TAG, "OCR result: " + ocredText);

			if (ocredText != null && !"".equals(ocredText)) {
				Message msg = handler.obtainMessage(2, 1, 0);
				msg.obj = ocredText;
				handler.sendMessage(msg);
			} else {
				Log.d("TAG", "OCR failed: empty string returned");
				Message msg = handler.obtainMessage(2, 0, 0);
				handler.sendMessage(msg);
			}
		} catch (Exception e) {
			Log.e("TAG", "OCR failed", e);
			Message msg = handler.obtainMessage(2, 0, 0);
			handler.sendMessage(msg);
		}

	}

	public String sendOcrRequest(Bitmap img) throws IOException {
		Log.i(TAG, "Sending OCR ");
		HttpPost post = createPost(img);

		BufferedReader reader = null;
		try {
			HttpResponse resp = httpClient.execute(post);
			reader = new BufferedReader(new InputStreamReader(resp.getEntity()
					.getContent(), "utf-8"));

			String status = reader.readLine();
			if (status.length() != 0) {
				status += readAllLines(reader);
				throw new RuntimeException("WeOCR failed. Status: " + status);
			}

			return readAllLines(reader);
		} catch (HttpResponseException re) {
			Log.e(TAG, "HTTP response exception", re);
			throw new RuntimeException("HTTP request failed. Status: "
					+ re.getStatusCode());
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
	}
	
    protected String readAllLines(BufferedReader reader) throws IOException {
        StringBuffer buff = new StringBuffer();
        String line = null;

        while ((line = reader.readLine()) != null) {
            buff.append(line);
            buff.append('\n');
        }

        return buff.toString().trim();
    }
    
    
    protected HttpPost createPost(Object param) throws IOException {
        HttpPost post = new HttpPost(url);
        return post;
    }

}
